import subprocess
import sys

from PyQt6 import QtWidgets
from PyQt6.QtCore import QTimer, QDate, Qt, QTime, QDateTime

from uidemo.timeEdit import Ui_timeEdit_2
from common.dolinux import get_beijing_time


class TimeEditImpl(QtWidgets.QWidget, Ui_timeEdit_2):
    def __init__(self):
        super().__init__()
        self.setupUi(self)  # 初始化界面
        self.init_ui()

        # 创建定时器，每秒更新时间
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.update_bjtime)
        self.timer.start(1000)  # 每 1000ms (1s) 触发一次

    def init_ui(self):
        # 初始化时间展示
        self.bjtime.setDateTime(get_beijing_time())
        self.dateTimeEdit.setDateTime(QDateTime.currentDateTime())

        # 绑定按钮事件
        self.btn_next_day.clicked.connect(self.next_day)
        self.btn_change_time.clicked.connect(self.change_time)

    def update_bjtime(self):
        """ 每秒增加 1 秒 """
        current_time = self.bjtime.dateTime()
        new_time = current_time.addSecs(1)  # 增加 1 秒
        self.bjtime.setDateTime(new_time)
        current_time3 = self.dateTimeEdit.dateTime()
        new_time3 = current_time3.addSecs(1)  # 增加 1 秒
        self.dateTimeEdit.setDateTime(new_time3)

    def next_day(self):
        current_time = self.dateTimeEdit.date()
        start_of_day = QDateTime(current_time, QDateTime.fromString("00:00:00", "hh:mm:ss").time())
        # 加 86380 秒
        target_time = start_of_day.addSecs(86380)
        self.dateTimeEdit.setDateTime(target_time)
        new_date_str = target_time.toString("yyyy-MM-dd")
        new_time_str = target_time.toString("HH:mm:ss")
        try:
            # 设置日期
            subprocess.run(f'date {new_date_str}', shell=True, check=True)
            # 设置时间
            subprocess.run(f'time {new_time_str}', shell=True, check=True)
        except Exception as e:
            raise e

    def change_time(self):
        current_time = self.dateTimeEdit.dateTime()
        new_date_str = current_time.toString("yyyy-MM-dd")
        new_time_str = current_time.toString("HH:mm:ss")
        try:
            # 设置日期
            subprocess.run(f'date {new_date_str}', shell=True, check=True)
            # 设置时间
            subprocess.run(f'time {new_time_str}', shell=True, check=True)
        except Exception as e:
            raise e


if __name__ == '__main__':
    # 创建应用和主窗口
    app = QtWidgets.QApplication(sys.argv)
    window = TimeEditImpl()
    window.show()

    # 运行应用
    sys.exit(app.exec())
